#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "protocol/include/mdqp.hpp"
#include "protocol/include/log.hpp"
#include "protocol/include/Market.hpp"

extern Market::Market &getMarket();

#define BUFFER_SIZE 409600

const int TCP_PORT = 12345;

int tcp_client()
{
    int client_sockfd;
    struct sockaddr_in server_addr;

    // 创建 TCP 套接字
    client_sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (client_sockfd == -1)
    {
        perror("socket");
        exit(1);
    }

    // 设置服务器地址和端口
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(TCP_PORT);               // 此处为服务器的端口号
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 此处为服务器的 IP 地址

    // 连接服务器
    if (connect(client_sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
    {
        perror("connect");
        exit(1);
    }

    printf("Connected to server.\n");

    std::vector<uint8_t> buffer(BUFFER_SIZE);
    while (1)
    {
        // 接收服务器的回复
        ssize_t read_len = recv(client_sockfd, buffer.data(), sizeof(MDQPHeader), 0);
        if (read_len == -1)
        {
            perror("recv");
            exit(1);
        }
        else if (read_len == 0)
        {
            LOG("Server disconnected.\n");
            break;
        }
        else
        {
            MDQPHeader *header = (MDQPHeader *)buffer.data();
            if (header->length == 0)
                continue;
            int need_data_len = header->length;

            // 打印header
            // LOG("MDQPHeader: flag_low=%d, flag_high=%d, type_id=%d, length=%d, request_id=%d\n",
            //     header->flag_low, header->flag_high, header->type_id, header->length, header->request_id);

            uint8_t *p = buffer.data() + sizeof(MDQPHeader);
            while (need_data_len > 0)
            {
                read_len = recv(client_sockfd, p, need_data_len, 0);
                if (read_len == -1)
                {
                    perror("recv");
                    LOG("Incomplete MDQP message. read_len = %d, header->length=%d\n", read_len, header->length);

                    break;
                }
                else if (read_len == 0)
                {
                    LOG("Server disconnected.\n");
                    break;
                }
                need_data_len -= read_len;
                p += read_len;
            }
            getMarket().parseMDQP(buffer.data(), header->length + sizeof(MDQPHeader));
        }
    }

    // 关闭客户端套接字
    close(client_sockfd);

    return 0;
}